package io.wins.vertx.verticle.api;

import io.vertx.core.Future;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.wins.vertx.entity.Classification;
import io.wins.vertx.service.ClassService;
import org.apache.commons.lang3.StringUtils;

public class ClassApiVerticle extends RestApiVerticle {
    public static final String REST_ADDRESS = "io.wins.rest.class#%1$s";
    private static final Logger logger = LoggerFactory.getLogger(ClassApiVerticle.class);

    public final ClassService service;

    public ClassApiVerticle(final ClassService classService) {
        this.service = classService;
    }

    @Override
    public void start(final Future<Void> future) throws Exception {
        super.start();
        this.on(String.format(REST_ADDRESS, CREATE), this::createClass);
        this.on(String.format(REST_ADDRESS, UPDATE), this::updateClass);
        this.on(String.format(REST_ADDRESS, LIST), this::listClass);
        this.on(String.format(REST_ADDRESS, DELETE), this::deleteClass);
        this.on(String.format(REST_ADDRESS, LOAD), this::loadClass);
        future.complete();
    }

    private void updateClass(final Message<JsonObject> tMessage) {
        final JsonObject body = tMessage.body().getJsonObject("body").getJsonObject("classData");
        final Classification c = new Classification(body);
        System.out.println(c.toJson());
        this.service.saveClass(c, tMessage);
    }

    private void loadClass(final Message<JsonObject> tMessage) {
        final JsonObject param = tMessage.body().getJsonObject("param");
        final String id = param.getString("id");
        this.service.loadClass(id, tMessage);
    }

    private void deleteClass(final Message<JsonObject> tMessage) {
        final JsonObject param = tMessage.body().getJsonObject("param");
        final String id = param.getString("id");
        this.service.disClasses(id, tMessage);
    }

    private void listClass(final Message<JsonObject> tMessage) {
        final JsonObject param = tMessage.body().getJsonObject("param");
        if (!StringUtils.isEmpty(param.getString("cust"))) {
            this.service.getCustClasses(tMessage);
        } else {
            this.service.getAllClasses(tMessage);
        }
    }

    private void createClass(final Message<JsonObject> tMessage) {
        final JsonObject body = tMessage.body().getJsonObject("body").getJsonObject("classData");
        final Classification c = new Classification(body);
        System.out.println(c.toJson());
        this.service.addClasses(c, tMessage);
    }
}
